﻿/*
 * log.c
 *
 *  Created on: 2017年4月9日
 *      Author: XJY
 */

#include "log.h"

FILE *G_LOG_OUT__;
int G_LOG_DETAIL = 0;

void setLogOut(char *filename) {
//	G_LOG_OUT__ = stdout;
	FILE *fd = NULL;

	if (filename != NULL) {
		fd = fopen(filename, "a+");
		if (fd == NULL) {
			G_LOG_OUT__ = stdout;
			logerr("errno = [%d][%s]\n", errno, strerror(errno));
		} else {
			G_LOG_OUT__ = fd;
		}
	} else {
		G_LOG_OUT__ = stdout;
	}
}

int closeLogOut2File() { //关闭文件描述符,不在向文件中写入日志
	if (G_LOG_OUT__ == stdout && G_LOG_OUT__ == stderr && G_LOG_OUT__ == stdin) {
		return 1; //cant close std
	} else {
		int closeStatus = fclose(G_LOG_OUT__);
		G_LOG_OUT__ = stdout;
		return closeStatus;
	}
}

int closeLogOut() { //只保留 logerr 信息,标准错误输出
	if (G_LOG_OUT__ == stdout && G_LOG_OUT__ == stderr && G_LOG_OUT__ == stdin) {
		return 1; //cant close std
	} else {
		int closeStatus = fclose(G_LOG_OUT__);
		return closeStatus;
	}

}

void setLogDetail(int mode) {
	G_LOG_DETAIL = mode;
}

int logGetDateTime(char *dtime, int len) {
	struct timeb tz;
	struct tm *p = NULL;

	if (dtime == NULL || len < DTIME_LEN) {
		return -2;
	}
	memset(dtime, 0x00, len);

	ftime(&tz);
	p = localtime(&(tz.time));

	sprintf(dtime, "%02d%02d%02d|%02d:%02d:%02d.%03d", 1900 + p->tm_year,
			1 + p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec,
			tz.millitm);

	return 0;
}

void loghex(unsigned char *data, int datalen, const char *msg) {
	int i = 0;
	if (msg != NULL) {
		loginfo("%s datalen = [%d], data = [", msg, datalen);
	} else {
		loginfo("datalen = [%d], data = [", datalen);
	}
	for (i = 0; i < datalen; i++) {
		logprint("%.2x ", data[i]);
	}
	logprint("]\n");
}
